package com.colter.project.sample.thread.part05.test1;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

//任务抛出异常
public class Test5 {
	public static void main(String[] args) {
		int[] array = new int[100];
		Task5 task = new Task5(array, 0, array.length);
		ForkJoinPool pool = new ForkJoinPool();
		pool.execute(task);
		pool.shutdown();
		try {
			pool.awaitTermination(1, TimeUnit.HOURS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if (task.isCompletedAbnormally()) {
			System.out.println("Main: An exception has ocurred.");
			System.out.println("Main: " + task.getException());
		}

		System.out.println("Main: Result:" + task.join());

	}
}

class Task5 extends RecursiveTask<Integer> {

	private static final long serialVersionUID = 1L;

	private int[] array;
	private int start, end;

	public Task5(int[] array, int start, int end) {
		super();
		this.array = array;
		this.start = start;
		this.end = end;
	}

	@Override
	protected Integer compute() {
		System.out.println("Task: start from " + start + " to " + end);
		if (end - start < 10) {
			if ((3 > start) && (3 < end)) {
				throw new RuntimeException("This task throws an Exception: from " + start + " to " + end);
			}

			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} else {
			int mid = (start + end) / 2;
			Task5 t1 = new Task5(array, start, mid);
			Task5 t2 = new Task5(array, mid, end);
			invokeAll(t1, t2);

		}
		System.out.println("Task: end form start " + start + " to " + end);
		return 0;
	}
}
